package com.ayf.payment.game.api.channel.longbao;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zh-liang
 * @Date : 2020-05-18 10:56
 */
@Slf4j
public class LongBaoHttpUtil {

    private static final String charSet = "GB2312";

    private static final CloseableHttpClient httpClient;

    //初始化超时时间配置，再根据配置生成默认的httpClient对象
    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    private static void setFormEntity(HttpPost httpPost, Map<String, String> params) throws UnsupportedEncodingException {
        List<NameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
        }
        if (pairs != null && pairs.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, charSet);
            httpPost.setEntity(entity);
        }
    }

    /**
     * HTTP POST 请求
     *
     * @param traceId 业务跟踪id
     * @param url     请求的url地址 ?之前
     * @param params  请求的参数
     * @return 响应内容
     */
    public static String doPost(String traceId, String url, Map<String, String> params) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            setFormEntity(httpPost, params);
            long start = System.currentTimeMillis();
            log.info("[{}]请求[{}]开始请求,请求参数为[{}]", traceId, url, params);
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, charSet);
            }
            EntityUtils.consume(entity);
            long end = System.currentTimeMillis();
            log.info("[{}]请求[{}]请求完成,耗时[{}]ms,请求参数为[{}],响应statusCode为[{}],响应内容为[{}]", traceId, url, end - start, params,
                    statusCode, result);
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient请求错误 status code :" + statusCode);
            }
            return result;
        } catch (Exception e) {
            log.error("[{}]请求[{}]发生[{}]异常,异常信息为[{}],请求参数为[{}],请求响应为[{}]", traceId, url, e.getClass(), e.getMessage(),
                    params, result);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("[{}]请求[{}]关闭连接时发生异常", traceId, url);
                }
            }
        }
        return null;
    }
}
